package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {


    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;


    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        /*1参数校验*/
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        /*2执行查询*/
        IPage<ApUserRealname> pageParam = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            query.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageParam, query);
        /*3返回结果*/
        return new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
    }

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */


    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1 参数检查
        if (dto == null || dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 查询当前认证用户是否在 APP端有当前用户
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null || apUserRealname.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        获取userID

        /*Integer userRealnameId = dto.getId();
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId,userRealnameId)
                .eq(ApUserRealname::getStatus,1)  // 状态为待审核
        );*/
        if (apUserRealname == null) {
            log.error(" apUserRealname is Null ");
            throw new CustomException(AppHttpCodeEnum.APUSERREALNAME_DATANOTEXIST_ERROR);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId())
                .eq(ApUser::getStatus, 0));

        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3 更新认证用户信息
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //4 认证状态如果为 通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //4.1 创建自媒体账户
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null) {
                throw new CustomException(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }

            //4.2 创建作者信息
            boolean flag = createApAuthor(wmUser);
            if (!flag) {
                throw new CustomException(AppHttpCodeEnum.APAUTHOR_ADD_ERROR);
            }
        }

        //5 更新APP用户状态
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);

        //TODO 发送通知消息

        //4 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 4.2 创建作者信息
     *
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        //1 查询当前作者是否存在，不存在则新增
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2); // 自媒体人类型
            apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
            apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
            ResponseResult result = articleFeign.save(apAuthor);
            // code=0
            if (result.getCode() == 0) {
                return true;
            }
        }

        return false;

    }

    /**
     * 4.1 创建自媒体账户
     *
     * @param dto
     * @param apUser APP端用户
     * @return
     */
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //2 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setSalt(apUser.getSalt());  // 盐
            wmUser.setPassword(apUser.getPassword()); // 密码
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setApUserId(apUser.getId());  // app端用户id
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
            wmUser = wemediaFeign.save(wmUser); // 主要的目的是返回新增后的主键

            if (wmUser.getId() != null) {
                return wmUser;
            }
        }

        return null;
    }
}
